// miniprogram/pages/addthing/addthing.js

const app = getApp();
var db = wx.cloud.database({
  env: "lemonbox-t-6wew9"
})
Page({

  /**
   * 页面的初始数据
   */
  data: {
    clsarray: [],
    clsIndex: 0,
    datearray: ['5天', '10天', '1个月', '3个月', '6个月', '9个月', '1年', '18个月', '2年'],
    dateVarray: [5, 10, 30, 90, 180, 270, 360, 540, 720],
    dateIndex: 0,
    bcheck: false,
    rcheck: false,
    name: '',
    barcode: '',
    count: 1,
    remark: '',
    price: '',
    images: [""],
    fileIDs: [],
    sdate: '',
    edate: '',
    buydate: '',
    thingId: null
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this
    db.collection('cls').orderBy('order', 'asc').get({
      success: res => {
        console.log(res)
        that.setData({
          clsarray: res.data
        })
      }
    })

    this.setData({
      images: []
    })
    var nowDate = new Date()
    var sDate = getDateFormat(nowDate)
    nowDate.setDate(nowDate.getDate() + this.data.dateVarray[0])
    var eDate = getDateFormat(nowDate)
    if (options.id) {
      db.collection('thing').doc(options.id)
        .get({
          success: function (res) {

            const data = res.data
            console.log(data)
            console.log(data.sdate)
            that.setData({
              thingId: options.id,
              clsIndex: data.cls.order,
              dateIndex:data.bcheck?data.dayIndex:0,
              bcheck: data.bcheck,
              rcheck: data.rcheck,
              name: data.name,
              barcode: data.barcode,
              count: data.count,
              remark: data.remark,
              price: data.price,
              images: data.fileIDs,
              fileIDs:data.fileIDs,
              sdate: data.bcheck?getDateFormat(new Date(data.startDate)):sDate,
              edate: data.bcheck?getDateFormat(new Date(data.endDate)):eDate,
              buydate: data.rcheck?getDateFormat(new Date(data.buyDate)):sDate,
            })

          }
        })
    }
    //
   

    this.setData({
      sdate: sDate,
      buydate: sDate,
      edate: eDate
    })

  },

  addImgs: function (e) {

    this.setData({
      images: e.detail.current
    })
    console.log(this.data.images)
  },

  save: function (e) {
    var that = this
    if (this.data.name == '') {
      wx.showToast({
        title: '请输入名称',
        icon: 'none'
      })
      return
    }
    console.log(this.data.images)
    //wxfile://tmp 手机端临时文件前缀
    if (this.data.images.length > 0 && this.data.images[0].indexOf("wxfile://tmp") != -1) {
      
      //图片安全检查

      wx.showLoading({
        title: '正在检查图片',
      })
      wx.serviceMarket.invokeService({
        service: 'wxee446d7507c68b11',
        api: 'imgSecCheck',
        data: {
          "Action": "ImageModeration",
          "Scenes": ["PORN", "POLITICS", "TERRORISM"],
          "ImageUrl": "",
          "ImageBase64": wx.getFileSystemManager().readFileSync(that.data.images[0], "base64"),
          "Config": "",
          "Extra": ""
        },
      }).then(res => {
        console.log(res)
        wx.hideLoading({
          success: (res) => {},
        })
        if(res.data.Response.Suggestion == 'BLOCK'){
          wx.showToast({
            title: '违规图片\n请重新选择',
            icon:'none'
          })
        }else{
          wx.showToast({
            title: '检查通过',
          })
          wx.showLoading({
            title: '正在上传图片',
          })
          let fileName = 'thing_cover_' + new Date().getTime() + '.png'
          wx.cloud.uploadFile({
            cloudPath: 'images/' + fileName, // 上传至云端的路径
            filePath: that.data.images[0], // 小程序临时文件路径
            success: function (res) {
              wx.hideLoading({
                success: (res) => {
                  wx.showToast({
                    title: '上传成功'
                  })
                },
              })
              var imgs = []
              imgs.push(res.fileID.replace("cloud://lemonbox-t-6wew9.6c65-lemonbox-t-6wew9-1303066479", "https://6c65-lemonbox-t-6wew9-1303066479.tcb.qcloud.la"))
              that.setData({
                fileIDs: imgs
              })
              that.addThing()
            },
            fail: function (e) {
              console.log(e)
              wx.hideLoading({
                success: (res) => {
                  wx.showToast({
                    title: '上传失败',
                    icon: 'none'
                  })
                },
              })
            }
          })
         
        }
      }).catch(err => {
        console.log('[err] 失败：', err)
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: '服务器出错\n稍后重试',
              icon:'none'
            })
          },
        })
      })
    } else {
      that.addThing()
    }
  },

  removeImg:function(e){
    var imgs = this.data.images
    imgs.splice(e.detail.current, 1); 
  },

  addThing: function () {
    var tips = '正在保存'
    const data = this.data
    if (data.thingId) {
      tips = '正在更新'
    }
    wx.showLoading({
      title: tips,
    })
    
    if (data.thingId) {
      console.log(data)
      db.collection('thing').doc(data.thingId).update({
        data:{
          name: data.name,
          cls: data.clsarray[data.clsIndex],
          count: data.count,
          startDate: data.bcheck ? getDate(data.sdate).getTime() : null,
          endDate: data.bcheck ? getDate(data.edate).getTime() : null,
          dayIndex: data.bcheck ? data.dateIndex : null,
          buyDate: data.rcheck ? getDate(data.buydate).getTime() : null,
          price: data.rcheck ? data.price : null,
          remark: data.rcheck ? data.remark : null,
          bcheck: data.bcheck,
          rcheck: data.rcheck,
          barcode: data.barcode,
          fileIDs: data.fileIDs,
          state: 0,
        },
        success:function(res){
          console.log(res)
          wx.showToast({
            title: '更新成功',
          })
          wx.navigateBack({
            delta: 1,
          })
        }
      })
    } else {
      db.collection('thing').add({
        data: {
          name: data.name,
          cls: data.clsarray[data.clsIndex],
          count: data.count,
          startDate: data.bcheck ? getDate(data.sdate).getTime() : null,
          endDate: data.bcheck ? getDate(data.edate).getTime() : null,
          dayIndex: data.bcheck ? data.dateIndex : null,
          buyDate: data.rcheck ? getDate(data.buydate).getTime() : null,
          price: data.rcheck ? data.price : null,
          remark: data.rcheck ? data.remark : null,
          bcheck: data.bcheck,
          rcheck: data.rcheck,
          barcode: data.barcode,
          fileIDs: data.fileIDs,
          state: 0,
          createTime: new Date()
        },
        success: function (res) {
          wx.hideLoading({
            success: (res) => {
              wx.showToast({
                title: '保存成功',
              })
              wx.navigateBack({
                delta: 1,
              })
            },
          })
        }
      })
    }

  },

  onCountChange: function (e) {
    this.setData({
      count: e.detail.count
    })
  },
  onNameChange: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  onPriceChange: function (e) {
    this.setData({

      price: e.detail.value
    })
  },
  bindEndDatePickerChange:function(e){
    this.setData({
      edate:e.detail.value
    })
  },

  onStartDatePickerChange: function (e) {
    this.setData({
      sdate: e.detail.value
    })
  },

  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      clsIndex: e.detail.value
    })
  },
  onDateChange: function (e) {
    this.setData({
      bcheck: e.detail.value
    })
  },
  bindBDateChange: function (e) {
    this.setData({
      dateIndex: e.detail.value
    })
    var nowDate = getDate(this.data.sdate)
    console.log(nowDate)
    nowDate.setDate(nowDate.getDate() + this.data.dateVarray[e.detail.value])
    this.setData({
      edate: getDateFormat(nowDate)
    })
  },
  onRemarkCheckChange: function (e) {
    this.setData({
      rcheck: e.detail.value
    })
  },
  scanCode: function (e) {
    var that = this;
    wx.scanCode({
      scanType: ['barCode'],
      success: (result) => {
        console.log(result)
        //查询
        wx.showLoading({
          title: '正在查询',
        })
        wx.cloud.callFunction({
          name: 'barcode',
          data: {
            barcode: result.result
          },
          complete: res => {
            wx.hideLoading({
              success: (res) => {},
            })
            console.log('callFunction test result: ', res)
            if (res.result.code == 0) {
              wx.showToast({
                title: '未收录',
                icon: 'none'
              })
            } else {
              that.setData({
                name: res.result.data.goodsName,
                barcode: result.result
              })
            }
          },
          error: res => {
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '查询失败',
                })
              },
            })
          }

        })
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  onRemarkChange: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  bindBuyDatePickerChange:function(e){
    this.setData({
      buydate:e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return{
      title:'物品收纳提醒实用工具',
      imageUrl:'https://website-178c6e-1252504509.tcloudbaseapp.com/images/lemonbox/sharecover.png',
      path:"/pages/index/index"
    }
  }
})

function getDateFormat(date) {
  return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
}

function getDate(strDate) {
  var year = strDate.split('-')[0]
  var month = strDate.split('-')[1] - 1
  var day = strDate.split('-')[2]
  return new Date(year, month, day)
}